import React, { PureComponent } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Form, Layout, Button, Table, Modal, DatePicker } from 'antd';
import { DEFAULT_PAGE_SIZE, CONST_PERMISSION_CODE_DUTY_NOTE_SHOW_ALL, CONST_DATE_FORMAT } from '@/constants';
import _ from 'lodash';
import styles from './index.less';

import Arrange from '../DutyShift/Item/Arrange';
import Edit from './edit';

const { Content } = Layout;
const { confirm } = Modal;
const { MonthPicker } = DatePicker;

class Index extends PureComponent {
  constructor(props) {
    super(props);
    this.modularName = 'dutyShift';
    const { global } = props;
    const { currentUnit = {} } = global;

    this.state = {
      data: {},
      time: moment(),
      currentUnitName: currentUnit.unit_name || '',
      query: {
        unit_id: {
          id: currentUnit.id || -1
        }
      }
    };
  }

  componentDidMount() {
    const { time } = this.state;
    const { global } = this.props;
    const { currentUnit = {} } = global;

    this.queryDataNew(time, currentUnit);
  }

  shouldComponentUpdate(nextProps, nextState) {
    console.info(this.props.modular.refreshTime, nextProps.modular.refreshTime)
    if (!_.isEqual(this.props.modular.refreshTime, nextProps.modular.refreshTime)) {
      const { time } = nextState;
      const { global } = nextProps;
      const { currentUnit = {} } = global;

      this.queryDataNew(time, currentUnit);
    }

    return !_.isEqual(this.props, nextProps) || !_.isEqual(this.state, nextState)
  }

  componentWillUnmount() {
    this.props.dispatch({ type: `${this.modularName}/clear` });
  }

  queryDataNew = (time, unit = {}) => {
    const { dispatch } = this.props;
    if (time) {
      dispatch({
        type: `${this.modularName}/queryDataNew`,
        payload: {
          startDate: moment(time).startOf('month').format(CONST_DATE_FORMAT),
          endDate: moment(time).endOf('month').format(CONST_DATE_FORMAT),
          shift_unit: { id: unit.id }
        }
      });
    }
  }

  onChange(date) {
    this.setState({ time: date }, () => {
      const { time } = this.state;
      const { global } = this.props;
      const { currentUnit = {} } = global;

      this.queryDataNew(time, currentUnit);
    });
  }

  appendBtnClick = () => {
    console.info('add');
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '排班管理', selectedData: {}, selectedTime: this.state.time },
    });
  };

  editBtnClick = record => {
    console.info(record);
    const { shift_date, shift_unit } = record;

    this.props.dispatch({
      type: `${this.modularName}/queryData`,
      payload: {
        startDate: moment(shift_date, 'YYYY-MM-DD').startOf('month').format(CONST_DATE_FORMAT),
        endDate: moment(shift_date, 'YYYY-MM-DD').endOf('month').format(CONST_DATE_FORMAT),
        shift_unit: { id: shift_unit },
        callback: (data) => {
          this.props.dispatch({
            type: `${this.modularName}/changeState`,
            payload: { visible: '排班管理', selectedData: { ...data[shift_date] }, selectedTime: moment(shift_date, 'YYYY-MM-DD') },
          });
        }
      }
    });
  };

  // 删除
  stopBtnClick = record => {
    confirm({
      title: '是否确定删除该条数据?',
      onOk: () => {
        const { dispatch } = this.props;
        dispatch({
          type: `${this.modularName}/deleteData`,
          payload: {
            data: {
              shift_date: record.shift_date,
              shift_unit: record.shift_unit,
              shift_id: record.shift_id,
              shift_title: record.shift_title,
            },
            callback: () => {
              const { time } = this.state;
              const { global } = this.props;
              const { currentUnit = {} } = global;

              this.queryDataNew(time, currentUnit);
            }
          },
        });
      },
    });
  };

  onOk = () => {
    const { dispatch, form, global, modular } = this.props;
    const { query } = this.state;
    const { currentUnit } = global;
    const { editData = {}, current, pageSize } = modular;

    form.validateFields({ force: true }, (err, values) => {
      if (!err) {
        const { ...data } = values;
        let { rememberConcat, rememberSource, rememberTitle, rememberType } = data;
        const remember = {};
        remember.unitId = query.unitId;
        if (values.filterTime || values.filterType) {
          let filterTime = values.filterTime;
          let filterType = values.filterType;
          if (values.filterTime) {
            remember.startTime = moment(filterTime[0]).format('YYYY-MM-DD' + ' 00:00:00');
            remember.endTime = moment(filterTime[1]).format('YYYY-MM-DD' + ' 23:59:59');
          }
          if (values.filterType) {
            remember.rememberType = filterType;
          }
        }

        if (editData.id) {
          dispatch({
            type: `${this.modularName}/saveOrUpdateData`,
            payload: {
              data: {
                id: editData.id,
                createTime: editData.createTime,
                rememberConcat,
                rememberSource,
                rememberTitle,
                rememberType,
                unitId: currentUnit.id,
              },
              remember,
              current,
              pageSize,
            },
          });
        } else {
          dispatch({
            type: `${this.modularName}/saveOrUpdateData`,
            payload: {
              data: {
                id: 0,
                createTime: '',
                rememberConcat,
                rememberSource,
                rememberTitle,
                rememberType,
                unitId: currentUnit.id,
              },
              remember,
              current,
              pageSize,
            },
          });
        }
      }
    });
  };

  render() {
    const { currentUnitName, query = {}, data, time } = this.state;
    const { dispatch, loading, form, global, modular } = this.props;
    const { currentUnit = {} } = global;
    const { visible, selectedTime, selectedData, refreshTime } = modular;
    const {
      rowKey,
      editData = {},
      newDataArr = []
    } = modular;
    const columns = [
      {
        title: '单位名称',
        dataIndex: 'unit_name',
        ellipsis: true,
        width: 320,
      },
      {
        title: '值班身份',
        dataIndex: 'title_name',
        ellipsis: true,
        width: 320,
      },
      {
        title: '姓名',
        dataIndex: 'name',
        ellipsis: true,
        width: 320,
      },
      {
        title: '手机号',
        dataIndex: 'mobile',
        ellipsis: true,
        width: 150,
      },
      {
        title: '值班地址',
        dataIndex: 'unit_address',
        ellipsis: true,
        width: 200,
      },
      {
        title: '班次',
        dataIndex: 'shift_name',
        ellipsis: true,
        width: 200,
      },
      {
        title: '值班日期',
        dataIndex: 'shift_date',
        ellipsis: true,
        width: 200,
      },
      {
        title: '值班固话',
        dataIndex: 'unit_phone',
        ellipsis: true,
        width: 200,
      },
      {
        title: '值班传真',
        dataIndex: 'unit_fax',
        ellipsis: true,
        width: 200,
      },
      {
        title: '操作',
        dataIndex: 'operate',
        align: 'center',
        width: 200,
        fixed: 'right',
        render: (text, record) => {
          return (
            <div className={styles.common_span_group}>
              <span onClick={this.editBtnClick.bind(this, record)}>编辑</span>
              <span style={{ color: '#ff4d4f' }} onClick={this.stopBtnClick.bind(this, record)}>
                删除
              </span>
            </div>
          );
        },
      },
    ];

    return (
      <Layout className={styles.basic_layout_wrapper}>
        <div className={styles.title}>
          当前单位: <span style={{ color: 'rgb(27, 139, 236)' }}>{currentUnit.unit_name}</span>
        </div>
        <Content className={styles.conditions_wrapper} style={{ margin: 0 }}>
          <Layout style={{ backgroundColor: 'transparent', height: '100%' }}>
            <div style={{ float: "left" }}>
              <div style={{ float: "left" }}>
                <Button
                  icon="plus"
                  type="primary"
                  style={{ width: 110, marginBottom: 16 }}
                  onClick={this.appendBtnClick}
                >
                  新增
                </Button>
              </div>
              <div style={{ marginBottom: 16, float: "right" }}>
                <MonthPicker
                  allowClear={false}
                  value={time}
                  onChange={this.onChange.bind(this)}
                />
              </div>
            </div>
            <Content className={styles.common_table_wrapper}>
              <Table
                columns={columns}
                dataSource={newDataArr}
                loading={
                  !!loading.effects[`${this.modularName}/queryDataNew`] ||
                  !!loading.effects[`${this.modularName}/deleteData`]
                }
                rowKey={rowKey}
                scroll={{ x: true }}
              />
            </Content>
          </Layout>
        </Content>
        <Modal
          centered
          destroyOnClose
          maskClosable={false}
          title={visible}
          visible={!!visible}
          wrapClassName={styles.common_modal_wrapper}
          width={1024}
          footer={null}
          onCancel={() => {
            dispatch({ type: `${this.modularName}/changeState`, payload: { visible: false, selectedData: {}/*, selectedTime: undefined*/ } })
          }}
        >
          <Arrange
            dispatch={dispatch}
            loading={loading}
            modularName={this.modularName}
            allowEdit={true}
            currentUnit={{ id: query.unit_id.id, unit_name: currentUnitName }}
            selectedData={selectedData}
            selectedTime={selectedTime}
          />
        </Modal>
      </Layout>
    );
  }
}

export default connect(({ loading, global, dutyShift }) => ({
  loading,
  global,
  modular: dutyShift,
}))(Form.create()(Index));
